<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Popconfirm } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { ApiKeyApi } from '#/api/system/api-key';

import APIKeyForm from './api-key-form.vue';
import APIKeyResult from './api-key-result.vue';

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入查询关键字',
      },
      label: '关键字',
      defaultValue: '',
      fieldName: 'query',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
};
const gridOptions: VxeGridProps<ApiKeyApi.ApiKeyResult> = {
  columns: [
    { field: 'client', title: '客户端' },
    { field: 'prefix', title: '令牌前缀' },
    { field: 'expired_at', title: '过期时间', formatter: 'formatDateTime' },
    {
      field: 'is_expired',
      title: '状态',
      formatter: ({ cellValue }) => (cellValue ? '已过期' : '正常'),
    },
    { slots: { default: 'action' }, title: '操作', width: 150 },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) =>
        ApiKeyApi.listApiKey({
          page: page.currentPage,
          page_size: page.pageSize,
          ...formValues,
        }),
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
const [EditModal, editModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: APIKeyForm,
});
const [ResultModal, resultModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: APIKeyResult,
});
function openApiKeyForm(row?: ApiKeyApi.ApiKeyResult) {
  editModalApi.setData(row ?? {}).open();
}

async function createApiKey(data: Partial<ApiKeyApi.ApiKeyResult>) {
  const apiKey = await ApiKeyApi.createApiKey(data);
  editModalApi.close();
  resultModalApi.setData({ apiKey }).open();
}

async function deleteApiKey(row: ApiKeyApi.ApiKeyResult) {
  await ApiKeyApi.deleteApiKey(row.id);
  gridApi.grid.remove(row);
}
</script>

<template>
  <Page title="用户组">
    <Grid>
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="gridApi.query()"> 刷新 </Button>
      </template>
      <template #toolbar-actions>
        <Button type="primary" @click="openApiKeyForm()" title="新增令牌"> 新增 </Button>
      </template>
      <template #action="{ row }">
        <Popconfirm @confirm="deleteApiKey(row)" title="确认删除？">
          <Button type="link" danger title="删除令牌">
            <IconifyIcon icon="fa6-solid:trash" />
          </Button>
        </Popconfirm>
      </template>
    </Grid>
    <EditModal @create="createApiKey" />
    <ResultModal @refresh="gridApi.query" />
  </Page>
</template>
